const c = require("child_process");
const fs = require("fs");
const os = require("os");
const path = require("path");
const dbFile = "db.json";
const dbPath = path.resolve(__dirname, dbFile);
function openUrl(url) {
  // 使用默认浏览器打开
  const ostype = os.type();
  if (ostype === "Windows_NT") {
    c.exec(`start ${url}`);
  } else {
    c.exec(`open ${url}`);
  }
}

/**
 * 获取JSON文件内的数据
 * @returns JSON对象
 */
function getItem() {
  const test = fs.readFileSync(dbPath, {
    encoding: "utf-8"
  });
  const obj = JSON.parse(test);
  return obj;
}

/**
 * 从文件中读取URL
 * @param {*} key
 * @returns 返回url如果没有就是undefined
 */
function getUrlFromkey(key) {
  const obj = getItem();
  return obj[key];
}
/**
 * 重置内容
 *
 */
function resetItem() {
  const obj = {};
  setFile(obj);
}

/**
 * 设置部分key
 * @param {*} key
 * @param {*} url
 */
function setItem(key, url) {
  const obj = getItem();
  obj[key] = url;
  setFile(obj);
}
/**
 * 导入文件
 * @param {*} path
 */
function importFile(path) {
  const content = fs.readFileSync(path, { encoding: "utf-8" });
  const obj = JSON.parse(content);
  setFile(obj);
}
/**
 * content是对象
 * @param {object} contentobj
 */
function setFile(contentobj) {
  fs.writeFileSync(dbPath, JSON.stringify(contentobj, null, 2), {
    encoding: "utf-8"
  });
}

module.exports = {
  openUrl,
  getItem,
  getUrlFromkey,
  resetItem,
  setItem,
  importFile,
  setFile
};
